package org.colcon.web.client.ui.deprecated;

import org.colcon.web.client.Collective_Congress;
import org.colcon.web.model.framework.IGroup;
import org.colcon.web.model.framework.IProposal;
import org.colcon.web.model.framework.ITitle;
import org.colcon.web.model.framework.IVote;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;

public class GroupInfoPanel extends InfoPanel 
{
	public GroupInfoPanel(Collective_Congress client, IGroup group) 
	{
		super(client, group);
		
		if(!group.hasMember(getClient().getUser().getId()))
		{
			Button joinButton = new Button("Join this group");
			joinButton.addClickHandler(new MyButtonHandler());
			add(joinButton);
		}
		
		add(new Label("Members"));
		for(String user : group.getMembers())
			add(new NamePanel(client, user));
		
		add(new Label("Titles"));
		for(ITitle title : group.getTitles())
			add(new NamePanel(client, title.getPath()));
		
		add(new Label("Proposals"));
		for(IProposal proposal : group.getProposals())
			add(new NamePanel(client, proposal.getPath()));
		
		add(new Label("Votes"));
		for(IVote vote : group.getVotes())
			add(new NamePanel(client, vote.getPath()));
	}
	
	public IGroup getGroup()
	{
		return (IGroup) getItem();
	}
	
	private class MyButtonHandler implements ClickHandler
	{
		public void onClick(ClickEvent event) 
		{
			joinGroup();
		}
	}
	
	public void joinGroup() 
	{
		getService().addMember(getGroup().getId(), getClient().getUser().getId(), new AsyncCallback<Boolean>()
		{
			public void onFailure(Throwable caught)
			{
				caught.printStackTrace();
			}
			
			public void onSuccess(Boolean result)
			{
				if(result)
				{
					getBodyPanel().clear();
					Label label = new Label("Group joined successfully");
					label.setStyleName("item");
					getBodyPanel().add(label);
				}
				else
				{
					getBodyPanel().clear();
					Label label = new Label("GFailed to join group");
					label.setStyleName("item");
					getBodyPanel().add(label);
				}
			}
		});
	}
}
